import React, { useRef, useEffect } from 'react';
import MessageBubble from './MessageBubble';
import './SimpleMessageList.css';

interface Message {
  content: string;
  isBot: boolean;
  timestamp: string;
  isStreaming?: boolean;
  isThinking?: boolean;
  id?: string;
}

interface SimpleMessageListProps {
  messages: Message[];
  className?: string;
}

const SimpleMessageList: React.FC<SimpleMessageListProps> = ({
  messages,
  className = '',
}) => {
  const messagesEndRef = useRef<HTMLDivElement>(null);

  // 自动滚动到底部
  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  };
  
  // 显示"回到底部"按钮
  const [showScrollButton, setShowScrollButton] = React.useState(false);
  
  // 检测滚动位置
  const containerRef = useRef<HTMLDivElement>(null);
  
  useEffect(() => {
    const container = containerRef.current;
    if (!container) return;
    
    const handleScroll = () => {
      const { scrollTop, scrollHeight, clientHeight } = container;
      const distanceFromBottom = scrollHeight - scrollTop - clientHeight;
      setShowScrollButton(distanceFromBottom > 100);
    };
    
    container.addEventListener('scroll', handleScroll);
    return () => container.removeEventListener('scroll', handleScroll);
  }, []);

  return (
    <div className={`simple-message-list ${className}`}>
      <div 
        ref={containerRef}
        className="messages-container"
      >
        {messages.map((message, index) => (
          <div 
            key={message.id || index}
            className="message-wrapper"
          >
            <MessageBubble
              content={message.content}
              isBot={message.isBot}
              timestamp={message.timestamp}
              isStreaming={message.isStreaming}
              isThinking={message.isThinking}
            />
          </div>
        ))}
        <div ref={messagesEndRef} />
      </div>
      
      {showScrollButton && (
        <button 
          className="scroll-bottom-button"
          onClick={scrollToBottom}
        >
          ↓
        </button>
      )}
    </div>
  );
};

export default React.memo(SimpleMessageList); 